<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 表达验证通过才会调用 -->
    <van-form @submit="onLogin"
    :show-error-message="false"
    :show-error="false"
    ref="login-form"
    :validate-first="true"
    @failed="onFailed"
    >
      <van-field
        v-model="user.mobile"
        class="iconfont"
        icon-prefix="icon"
        left-icon="shouji"
        placeholder="请输入手机号"
        center
        name="mobile"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        clearable
        class="iconfont"
        icon-prefix="icon"
        left-icon="yanzhengma"
        center
        name="code"
        placeholder="请输入验证码"
        :rules="formRules.code">
       <template #button>
          <van-count-down
          v-if="isCountDownShow"
          :time="1000 * 60"
          format="ss s"
          @finish="isCountDownShow = false"/>
          <van-button
            v-else
            class="send-btn"
            size="mini"
            round
            :loading="isSendSmsLoading"
            @click.prevent="onSendSms"
          >发送验证码</van-button>
        </template>
      </van-field>
    <div class="login-btn-wrap">
      <van-button class="login-btn"
        type="info"
        block>登录
      </van-button>
    </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
import { Toast } from 'vant'

export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3\5\7\9]\d{9}$/, message: '手机号格式错误' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' }
        ]
      },
      isCountDownShow: false, // 控制倒计时
      isSendSmsLoading: false // 发送按钮的false
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLogin () {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0// 为0 不会消失
      })
      // ● 注册登录按钮点击事件
      // ● 获取表单数据（根据接口要求使用 v-model 绑定）
      // ● 表单验证
      // ● 请求提交
      try {
        const { data } = await login(this.user)
        Toast.success('登录成功')
        // 将后端返回的状态 存储到vuex中
        this.$store.commit('setUser', data.data)
        // 清除layout
        this.$store.commit('removeCachePage', 'LayoutIndex')
        this.$router.back()
      } catch (err) {
        console.log(err)
        Toast.fail('登陆失败')
      }
      // ● 处理响应结果
    },

    onFailed (err) {
      if (err.errors[0]) {
        Toast({
          message: err.errors[0].message,
          position: 'top'
        })
      }
    },

    async onSendSms () {
      try {
        // 校验手机号码
        await this.$refs['login-form'].validate('mobile')
        this.isSendSmsLoading = true // 展示按钮的loading状态
        // 验证通过 -> 请求发送验证码 -> 用户接收短信 -> 输入验证码 -> 请求登录
        await sendSms(this.user.mobile)
        // 请求发送验证码 -> 隐藏发送按钮，显示倒计时
        this.isCountDownShow = true
        // 倒计时结束 -> 隐藏倒计时，显示发送按钮
      } catch (err) {
        console.dir(err)
        let msg = ''
        // 进行错误的判断
        if (err && err.response && Number.parseInt(err.response.status) === 429) {
          msg = '发送太频繁了请稍后重试'
        } else if (err.name === 'mobile') {
          msg = err.message
        } else if (Number.parseInt(err.response.status) === 404) {
          msg = '手机号错误，请重新尝试'
        } else {
          msg = '未知错误，请重新尝试'
        }
        this.$toast({
          message: msg,
          position: 'top'
        })
      }
      this.isSendSmsLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
